<?php
/**
 * Created by 惠达浪
 * Email: crazys@126.com
 * Date: 2018/12/1
 * Time: 18:23
 */

namespace app\api\logic;


use app\api\model\ClassModel;
use app\api\model\Mesworksheet;
use app\api\model\Result;
use app\api\model\ResultProductReport;
use app\api\model\ResultReport;
use app\lib\enum\MesEnum;
use think\Exception;

class Mes {
    /**
     * 根据用户id获取任务列表
     *
     * @param int $workcenter_id 工作中心id
     *
     * @return Result[]|false
     * @throws \think\Exception\DbException
     */
    public function getTaskLists($workcenter_id) {
        //获取当前时间对应的班次
        $class = ClassModel::where('workcenter_id', 'eq', $workcenter_id)
            ->whereBetweenTimeField('cls_begin', 'cls_end')->find();
        if ($class) {
            $lists = Result::where('workcenterid', '=', $workcenter_id)
                ->whereBetweenTime('starttime_year_month', $class['cls_begin'], $class['cls_end'])
                ->with(['mesworksheet', 'mesprocess'])
                ->select();
            return $lists;
        }
        return false;
    }

    /**
     * 获取当前工作任务
     *
     * @param int $workcenter_id 工作中心id
     *
     * @return array|null
     */
    public function getRecentTask($workcenter_id) {
        $task['current'] = Result::where('workcenterid', '=', $workcenter_id)
            ->where('endtime_year_month', 'gt', time())
            ->orderRaw('abs(now()-starttime_year_month) asc')
            ->with(['mesworksheet', 'mesprocess.mescomponent.component'])
            ->find();
        $task['next'] = Result::where('workcenterid', '=', $workcenter_id)
            ->where('id', '>', $task['current']['id'])
            ->with(['mesworksheet', 'mesprocess.mescomponent.component'])
            ->find();

        return $task;
    }

    /**
     * 根据工单号码获取该工单下的所有详细信息
     *
     * @param int $planid 工单号码
     *
     * @return array
     * @throws \think\Exception\DbException
     */
    public function getWorkSheetDetailById($planid) {
        $detail = Mesworksheet::get($planid, ['erpmain']);
        return ['image' => $detail['erpmain']['image']];
    }

    /**
     * 开始任务
     *
     * @param int   $result_id 任务id
     * @param array $userIds   用户id集
     *
     * @return bool
     * @throws \think\exception\PDOException
     * @throws \Exception
     */
    public function taskStart($result_id, array $userIds) {
        $resultModel = new Result();
        $resultModel->startTrans();
        try {
            //生成各用户的数据
            $now = time();
            $data = [];
            foreach ($userIds as $uid) {
                $data[] = [
                    'result_id' => $result_id,
                    'rpr_starttime' => $now,
                    'rpr_status' => MesEnum::REPORT_UNFINISHED,
                    'user_id' => $uid
                ];
            }

            //保存数据
            $updateResult = $resultModel->save(['status' => MesEnum::RESULT_START], ['id' => $result_id]);
            $rprModel = new ResultProductReport();
            $createRPR = $rprModel->isUpdate(false)->saveAll($data);

            if ($updateResult && $createRPR) {
                $resultModel->commit();
                return true;
            } else {
                $resultModel->rollback();
                return false;
            }
        } catch (Exception $e) {
            $resultModel->rollback();
            return false;
        }
    }

    /**
     * 报产业务处理
     *
     * @param int   $result_id 任务id
     * @param array $userIds   报产时的用户id集
     * @param int   $quantity  报产产量
     *
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function reportResult($result_id, array $userIds, $quantity) {
        //报产默认状态：未完成
        $status = MesEnum::REPORT_UNFINISHED;
        //生成各用户的数据
        $now = time();
        $rprModel = new ResultProductReport();
        $rprModel->startTrans();
        try {
            $success = true;
            //取出历史报产记录，计算总产量
            $rrModel = new ResultReport();
            $total = $rrModel->totalQuantity($result_id, $quantity);
            //取出计划产量
            $plan = Result::get($result_id, 'mesprocess');
            $planQuantity = $plan['mesprocess']['msp_quantity'];
            //如果报产总量等于计划总量，则任务完成
            if ($total >= $planQuantity) {
                $status = MesEnum::REPORT_FINISHED;
                $resultStatus = MesEnum::RESULT_FINISHED;
            } else {
                $resultStatus = MesEnum::RESULT_HAS_REPORTED;
            }
            Result::update(['status' => $resultStatus], ['id' => $result_id]);

            //保存报产记录
            $result = $rrModel->save([
                'result_id' => $result_id,
                'quantity' => $quantity
            ]);
            if (!$result) {
                $rprModel->rollback();
                return false;
            }

            //每个登录者更新报产
            foreach ($userIds as $uid) {
                $data = [
                    'rpr_endtime' => $now,
                    'rpr_status' => $status,
                    'rpr_quantity' => $quantity
                ];
                $where = [
                    'result_id' => $result_id,
                    'user_id' => $uid,
                    'rpr_endtime' => 0
                ];
                $result = $rprModel->save($data, $where);
                if (!$result) {
                    $success = false;
                }
            }

            if ($success) {
                $rprModel->commit();
                return true;
            } else {
                $rprModel->rollback();
                return false;
            }
        } catch (\Exception $e) {
            $rprModel->rollback();
            return false;
        }
    }

    /**
     * 获取指定id的任务状态
     *
     * @param int $result_id 任务id
     *
     * @return mixed
     */
    public function getResultStatus($result_id) {
        return Result::where('id', '=', $result_id)->value('status');
    }
}